import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Input,
  Button,
  Table,
  Card,
  message,
  Icon,
  Pagination,
  Radio,
  Form,
  Modal,
  Spin,
  Switch,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { FormattedMessage } from 'umi-plugin-react/locale';
import moment from 'moment';
const confirm = Modal.confirm;
import PageLoading from '@/components/PageLoading';
import styles from '../../KnowledgeManagement/Overview/qaList/index.less';
import del1Img from '@/assets/knowledge/del1.png';
import editImg from '@/assets/knowledge/edit.png';
import moreImg from '@/assets/knowledge/more.png';
import addImg from '@/assets/knowledge/add.png';
import searchImg from '@/assets/knowledge/search.png';
import RobotBtn from '@/utils/robotBtn';
import Bottword from '@/modules/Bottword.js';

const Search = Input.Search;
const CollectionCreateForm = Form.create({ name: 'form_in_modal' })(
  class extends React.Component {
    render() {
      const { visible, onCancel, onCreate, form,userInfo,isEdit,loading } = this.props;
      const { getFieldDecorator } = form;
      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 },
        },
      };
      return (
        <Modal
          visible={visible}
          title="添加编辑用户"
          okText="保存"
          onCancel={onCancel}
          onOk={onCreate}
        >
          <Spin spinning={loading}>
            <Form {...formItemLayout}>
              {isEdit?<Form.Item label="用户昵称">
                {getFieldDecorator('nick', {
                  initialValue:userInfo.nick,
                  rules: [{ required: true, message: '用户名必填' }],
                })(<Input placeholder='请输入用户的中文昵称，一般输入用户的真实姓名'   />)}
              </Form.Item>:
              <Form.Item label="用户昵称">
                {getFieldDecorator('nick', {
                  initialValue:'',
                    rules: [{ required: true, message: '用户名必填' }],
                  })(<Input placeholder='请输入用户的中文昵称，一般输入用户的真实姓名'  />)}
              </Form.Item>
                }
              {isEdit?<Form.Item label="登录邮箱">
                {getFieldDecorator('mail', {
                  initialValue:userInfo._id,
                  rules: [{ required: true, message: '登录邮箱必填' }],
                })(<Input placeholder='登录邮箱是用户的登录账号'  />)}
              </Form.Item>:
              <Form.Item label="登录邮箱">
                {getFieldDecorator('mail', {
                  initialValue:'',
                    rules: [{ required: true, message: '登录邮箱必填' }],
                  })(<Input placeholder='登录邮箱是用户的登录账号'  />)}
              </Form.Item>
              }
              {isEdit?<Form.Item label="登录密码">
                {getFieldDecorator('password', {
                  initialValue:userInfo._id,
                  rules: [{ required: false, message: '登录密码必填' }],
                })(<Input.Password disabled placeholder='请输入用户的登录密码'   />)}
              </Form.Item>:
              <Form.Item label="登录密码">
                {getFieldDecorator('password', {
                  initialValue:'',
                    rules: [{ required: true, message: '登录密码必填' }],
                  })(<Input.Password placeholder='请输入用户的登录密码' autoComplete="new-password" />)}
              </Form.Item>
                }
              <Form.Item className="collection-create-form_last-form-item" label="用户角色">
                {getFieldDecorator('role', {
                  initialValue: 'Robot_QA',
                })(
                  <Radio.Group>
                    <Radio value="Robot_QA">知识维护</Radio>
                  </Radio.Group>,
                )}
              </Form.Item>
            </Form>
          </Spin>
        </Modal>
      );
    }
  },
);


@connect(({ management, loading }) => ({
  management,
  loading: loading.effects['management/getUsers'],
}))




class Users extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      notices:[],
      tableLoading:true,
      total:0,
      visible: false,
      searchText: '',
      userInfo: {},
      isEdit: false,
      loading:true,
      pageSize:10,
      auth: true
    };
    this.columns = [
      {
        key: 'index',
        align: 'left',
        title: '序号',
        dataIndex: '',
        render: (key,index,text) => {
          text ++;
          return text;
        },
      },
      {
        key: '_id',
        align: 'left',
        title: '账户',
        dataIndex: '_id',
      },
      {
        key: 'nick',
        align: 'left',
        title: '用户名称',
        dataIndex: 'nick',
      },
      // {
      //   key: 'rolesDes',
      //   align: 'left',
      //   title: '用户角色',
      //   dataIndex: 'rolesDes',
      // },
      // {
      //   key: 'departmentName',
      //   align: 'left',
      //   title: '所属业务',
      //   dataIndex: 'departmentName',
      // },
      {
        key: 'addTime',
        align: 'left',
        title: '创建时间',
        dataIndex: 'addTime',
        render: (dataIndex) => {
          return moment(parseInt(dataIndex)).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        align: 'left',
        render: (text, row) => {
          return <div>
            <div className={styles.tool}>
              <img src={editImg} alt="编辑知识点" style={{marginRight:5,cursor:"pointer"}} onClick={() => this.queryUser(row)} />
              <img src={del1Img} alt="删除知识点" style={{marginRight:5,cursor:"pointer"}} onClick={() => this.showDeleteConfirm(row)} />
              {/*<Switch checked={row.disabled} checkedChildren="启用" unCheckedChildren="停用" onChange={(value) => this.showDeleteConfirm(row,value)} />*/}
            </div>
            <img src={moreImg} alt="" className={styles.more} />
          </div>
        },
        width: '100px',
      },
    ];
  }

  componentDidMount() {
    this.getUsers();
  }

  showModal = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.setState({ visible: true,loading:false ,userInfo:{}});
  };

  handleCancel = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.setState({ visible: false ,isEdit: false,userInfo:{}});
  };

  handleCreate = () => {
    const form = this.formRef.props.form;
    const type = this.state.isEdit;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      if(type){
        this.editUser(values)
      }else{
        this.addUser(values);
      }
      form.resetFields();
      this.setState({ visible: false });
    });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  onChangeForPage=(number)=>{
    console.log(number);
    this.setState({
      page:number,
      tableLoading:true,
    },()=>{
      this.getUsers();
    })
  };

  onShowSizeChangeForPage=(current,size)=>{
    this.setState({
      page:current,
      pageSize:size,
      tableLoading:true,
    },()=>{
      this.getUsers();
    })
  };

  getUsers=()=>{
    const { dispatch} = this.props;
    dispatch({
      type: 'management/getUsers',
      payload: {page:this.state.page,limit:this.state.pageSize,search:this.state.searchText},
      callback:(res)=>{
        this.setState({
          notices: res.list,
          total:res.total,
          tableLoading: false
        })
      }
    });
  };

  addUser=(obj)=>{
    const { dispatch,currentUser} = this.props;
    dispatch({
      type: 'management/addUser',
      payload: {mail:obj.mail,nick:obj.nick,password:obj.password},
      callback:(res)=>{

        if(res.msg || res.msg !== undefined){
          return message.error(res.msg)
        }
        message.info('添加成功');
        this.getUsers();
        // message.info('添加成功');
        // this.getUsers()
      }
    });
  };

  delUser=(row)=>{
    const { dispatch} = this.props;
    dispatch({
      type: 'management/delUser',
      payload: {deleteUserId:row._id},
      callback:(res)=>{
        if(res.status){
         return this.getUsers()
        }
        return message.error(res.msg)
      }
    });
  };

   showDeleteConfirm =(row)=> {
     const  that = this;
    confirm({
      title: '确认删除'+row.nick+'该账号么',
      content: '',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        console.log('OK');
        that.delUser(row)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  resetUser=(row)=>{
    const { dispatch} = this.props;
    dispatch({
      type: 'management/resetUser',
      payload: {userId:row._id},
      callback:(res)=>{
        if(res.status){
          return message.info(res.msg)
        }
        return message.error(res.msg)
      }
    });
  };

  editUser=(row)=>{
    const { dispatch,currentUser} = this.props;
    let arr= [];
    arr.push(row.role);
    dispatch({
      type: 'management/editUser',
      payload: {targetUserId:row.mail,nick:row.nick},
      callback:(res)=>{
        if(res.status){
          message.info(res.msg);
          this.getUsers()
        }else{
          this.setState({
            auth: false
          });
          message.error(res.msg)
        }
      }
    });
  };

  queryUser=(row)=>{
    const { dispatch} = this.props;
    this.setState({ visible: true,isEdit: true,loading:true});
    dispatch({
      type: 'management/queryUser',
      payload: {userId:row._id},
      callback:(res)=>{
        this.setState({ userInfo:res,loading:false });
      }
    })
  };

  setSearch=(val)=>{
    this.setState({
      searchText: val
    },()=>{
      this.getUsers();
    })
  };

  setQuery=(e)=>{
    this.setState({
      searchText:e.target.value
    })
  };

  render() {
    const {notices,tableLoading,page,total,pageSize,userInfo,isEdit,loading} = this.state;
    return (
      <Suspense fallback={<PageLoading />}>
        <p className={styles.pageTitle}>用户管理</p>
        <Row style={{marginBottom:10}}>
          <Col span={4}>
            <Input
              placeholder="请输入姓名或账号"
              style={{ width: 268,marginBottom:20 }} onChange={this.setQuery}
              suffix={
                <img src={searchImg} style={{cursor:"pointer",width:20}} alt="" onClick={()=>this.setSearch(this.state.searchText)} />
              }
            />
          </Col>
          <Col offset={18} span={2}>
            <img
              onClick={this.showModal}
              style={{ cursor: 'pointer',marginRight: -10 }}
              src={addImg}
            />
          </Col>
        </Row>
            <Table
              columns={this.columns}
              dataSource={notices}
              className="zdyTable"
              rowKey="_id"
              pagination={false}
              // pagination={{  // 分页
              //   total,
              //   pageSize,  // 显示几条一页
              //   defaultPageSize: parseInt(page), // 当前页
              //   showSizeChanger: true,  // 是否显示可以设置几条一页的选项
              //   showQuickJumper: true,
              //   onChange: this.onChangeForPage,
              //   onShowSizeChange: this.onShowSizeChangeForPage
              // }}
              loading={tableLoading}
            />
        <Pagination
          style={{ textAlign: 'center', marginTop: 20, marginBottom: 20 }}
          total={this.state.total}
          pageSize={this.state.pageSize} // 显示几条一页
          current={this.state.page} // 当前页
          showSizeChanger={true} // 是否显示可以设置几条一页的选项
          onChange={this.onChangeForPage}
          onShowSizeChange={this.onShowSizeChangeForPage}
          showTotal={() => `共 ${this.state.total} 条`}
        />
            <CollectionCreateForm
              wrappedComponentRef={this.saveFormRef}
              visible={this.state.visible}
              onCancel={this.handleCancel}
              onCreate={this.handleCreate}
              userInfo={userInfo}
              isEdit={isEdit}
              loading={loading}
            />
      </Suspense>
    );
  }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(Users);
